package vip.liux.front.adapter.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.liux.front.application.listeners.events.AsyncEvent;

import static vip.liux.front.infrastructure.constants.MqExchangeConst.MESSAGE_ASYNC_NOTIFY;

@RestController
@RequestMapping("/api/message")
public class MessageController {

    private final RabbitTemplate rabbitTemplate;
    private final ApplicationEventPublisher applicationEventPublisher;

    public MessageController(RabbitTemplate rabbitTemplate, ApplicationEventPublisher applicationEventPublisher) {
        this.rabbitTemplate = rabbitTemplate;
        this.applicationEventPublisher = applicationEventPublisher;
    }

    @RequestMapping("/send/mq")
    public ResponseEntity<?> sendMq(String message) {
        rabbitTemplate.convertAndSend(
                MESSAGE_ASYNC_NOTIFY,
                message);
        return ResponseEntity.noContent().build();
    }

    @RequestMapping("/send/event")
    public ResponseEntity<?> sendEvent(String message) {
        applicationEventPublisher.publishEvent(new PayloadApplicationEvent<String>(this, message));
        return ResponseEntity.noContent().build();
    }


    @RequestMapping("/send/event/sync")
    public ResponseEntity<?> sendEventSync(String message) {
        applicationEventPublisher.publishEvent(new AsyncEvent(this, message));
        return ResponseEntity.noContent().build();
    }
}
